const router = require('koa-router')()
const koa2Req = require('koa2-request');
const axios = require("axios");
const { login, getImages, getServers, getNetworks, deleteImage, createImage, connectVNC } = require('../http/api')
const fs = require('fs')
const { createFirstMenu,createPage } = require('../utils/menu')
const { respondTableOk, respondOk } = require('../utils/responseTemplate')
const Qs = require("qs");　　//qs是一个url参数转化（parse/stringify）的js库


router.prefix('/users')
let token = fs.readFileSync('./cache', 'utf-8') || null



/**
 * 首页接口
 */
 router.get('/home', async function (ctx, next) {
  const projects = [
    {
      id:'2323352542523',
      name:"xiezh01",
      description:"xxxxxxx"
    },
    {
      id:'2323352542523',
      name:"xiezh02",
      description:"sssssxxxxxxx"
    },
    {
      id:'2323352542523',
      name:"xiezh03",
      description:"wwwwwxxxxxxx"
    }, 
  ]
  ctx.body = respondOk(projects)
})

/**
 * 登录接口
 */
router.post('/login', async function (ctx, next) {
  const params = ctx.request.body
  console.log('params', params);
  // const data = await login(params)
  // token = data.access_token
  token =' data.access_token'
  fs.writeFileSync('./cache', token)
  ctx.body = {
    code: 200,
    result: {
      token,
      // token: data.access_token,
      userInfo: {
        username: 'data.user.username'
      }
    }
  }
})

/**
 * 获取权限接口
 */
router.get('/getUserPermissionByToken', function (ctx, next) {
  ctx.body = {
    "success": true,
    "message": "查询成功",
    "code": 200,
    "result": {
      "allAuth": [{
        "action": "online:goGenerateCode",
        "describe": "代码生成按钮",
        "type": "1",
        "status": "1"
      }, {
        "action": "user:add",
        "describe": "添加按钮",
        "type": "1",
        "status": "1"
      }, {
        "action": "user:edit",
        "describe": "用户编辑",
        "type": "1",
        "status": "1"
      }, {
        "action": "user:sex",
        "describe": "表单性别可见",
        "type": "1",
        "status": "1"
      }, {
        "action": "user:form:birthday",
        "describe": "禁用生日字段",
        "type": "2",
        "status": "1"
      }, {
        "action": "user:form:phone",
        "describe": "手机号禁用",
        "type": "2",
        "status": "1"
      }],
      "auth": [{
        "action": "online:goGenerateCode",
        "describe": "代码生成按钮",
        "type": "1"
      }, {
        "action": "user:add",
        "describe": "添加按钮",
        "type": "1"
      }],
      "menu": [
        // createFirstMenu('首页', "/dashboard/analysis", "dashboard/Analysis"),
        createFirstMenu('首页', "home/home", "home/Home"),
        // createFirstMenu('虚拟机管理', "/servers/serverlist", "servers/ServersList"),
        // createFirstMenu('镜像管理', "/imagelist/imagelist", "imagelist/ImageList"),
        // createFirstMenu('网络管理', "/network/networklist", "network/NetworkList"),
        // createFirstMenu('路由管理', "/router/routerlist", "router/RouterList"),
        // createFirstMenu('项目详情', "project-detail", "projectDetail/ProjectDetail"),
        createFirstMenu('项目列表', "project-list", "projectList/ProjectList"),
        // createFirstMenu('配置项目环境', "create-env", "createEnv/CreateEnv"),
        {
          "redirect": null,
          "path": "/projects",
          "component": "layouts/RouteView",
          "route": "1",
          "hidden": true,
          "children": [
            {
              "path": "project-detail",
              "component": "projectDetail/ProjectDetail",
              "route": "1",
              "meta": {
                "keepAlive": false,
                "internalOrExternal": false,
                "componentName": "Index",
                "title": "项目详情"
              },
              "name": "project-detail",
              "id": "d86f58e7ab516d3bc6bfb1fe10585f97"
            },
            {
              "path": "create-env",
              "component": "createEnv/CreateEnv",
              "route": "1",
              "meta": {
                "keepAlive": false,
                "internalOrExternal": false,
                "componentName": "Index",
                "title": "项目详情"
              },
              "name": "create-env",
              "id": "d86f58e7ab516d3bc6bfb1fe10585f95"
            },
          ],
          "meta": {
            "keepAlive": false,
            "internalOrExternal": false,
            "icon": "user",
            "componentName": "RouteView",
            "title": "个人页"
          },
          "name": "account",
          "id": "717f6bee46f44a3897eca9abd6e2ec44"
        }
      ]
    },
    "timestamp": 1624330126166
  }
})

/**
 * 获取镜像列表接口
 */
router.get('/imagelist/imagelist/list', async function (ctx, next) {
  const { code, data } = await getImages(token);
  // console.log(data);
  if (code === 0) {
    ctx.body = respondTableOk(data)
  } else if (code === 401) {
    const loginData = await login()
    token = loginData.access_token
    fs.writeFileSync('./cache', token)
    const { code, data } = await getImages(token);
    ctx.body = respondTableOk(data)

    // ctx.body = {
    //   "success": true,
    //   "message": "登录过期",
    //   "code": 401,
    //   "result": {},
    //   "timestamp": Date.parse(new Date)
    // }
  } else {
    ctx.body = {
      "success": true,
      "message": "其他错误",
      "code": -1,
      "result": {},
      "timestamp": Date.parse(new Date)
    }
  }
})

/**
 * 删除镜像接口
 * todo 未完成
 */
router.delete('/imagelist/imagelist/delete', async function (ctx, next) {
  console.log('删除的镜像id：', ctx.request.query.id);
  const imageId = ctx.request.query.id
  const data = await deleteImage(imageId, token);
  // console.log(data);
  ctx.body = respondOk(data)
})


/**
 * 获取虚拟机列表接口
 */
router.get('/servers/servers/list', async function (ctx, next) {
  const res = await getServers(token)
  // console.log(data);
  ctx.body = respondTableOk(res.data)
})

/**
 * 获取虚拟机规格列表接口
 */
router.get('/flavors/flavors/list', async function (ctx, next) {
  // console.log(data);
  ctx.body = { "success": true, "message": "操作成功！", "code": 200, "result": { "records": [{ "createBy": "admin", "memorysize": "1024000", "size": "100", "createTime": "2021-06-22 10:41:05", "updateBy": null, "name": "1c_1g_100F", "sysOrgCode": "A01", "cpu": "8", "updateTime": null, "id": "1407166719880413185" }], "total": 1, "size": 10, "current": 1, "orders": [], "optimizeCountSql": true, "hitCount": false, "countId": null, "maxLimit": null, "searchCount": true, "pages": 1 }, "timestamp": 1624330203451 }
})

/**
 * 获取网络管理接口
 */
router.get('/network/networklist/list', async function (ctx, next) {
  const res = await getNetworks(token)
  // console.log(data);
  if (res.code === 0) {
    ctx.body = respondTableOk(res.data)
  } else {
    ctx.body = respondTableOk({})
  }
})

/**
 * 获取网络管理接口
 */
router.get('/router/router/list', async function (ctx, next) {
  const res = await getNetworks(token)
  // console.log(data);
  if (res.code === 0) {
    ctx.body = respondTableOk(res.data)
  } else {
    ctx.body = respondTableOk({})
  }
})

/**
 * 生成虚拟机镜像
 */
router.get('/images/create', async function (ctx, next) {
  const id = ctx.request.query.id
  const res = await createImage(id, token)
  // console.log(data);
  if (res.code === 0) {
    ctx.body = respondOk(res)
  } else {
    ctx.body = respondOk(res)
  }
})


/**
 * 查询VNC界面的地址
 */
router.get('/servers/vnc', async function (ctx, next) {
  const id = ctx.request.query.id
  const res = await connectVNC(id, token)
  // console.log(data);
  if (res.code === 0) {
    ctx.body = respondOk(res)
  } else {
    ctx.body = respondOk(res)
  }
})

module.exports = router
